package com.example.hospital.mapper;

import com.example.hospital.domain.entity.Sample;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface SampleMapper {
    @Insert("INSERT INTO sample (order_id, sample_type, collection_time, status, remark, create_time) VALUES (#{orderId}, #{sampleType}, #{collectionTime}, #{status}, #{remark}, NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "sampleId")
    int insert(Sample sample);

    @Update("UPDATE sample SET status=#{status}, remark=#{remark} WHERE sample_id=#{sampleId}")
    int updateStatus(@Param("sampleId") Long sampleId, @Param("status") Integer status, @Param("remark") String remark);

    @Select("SELECT * FROM sample WHERE sample_id=#{sampleId}")
    Sample findById(@Param("sampleId") Long sampleId);

    @Select({
            "<script>",
            "SELECT * FROM sample",
            "<where>",
            "  <if test=\"sampleId != null\"> AND sample_id = #{sampleId} </if>",
            "  <if test=\"orderId != null\"> AND order_id = #{orderId} </if>",
            "  <if test=\"sampleType != null and sampleType != ''\"> AND sample_type = #{sampleType} </if>",
            "  <if test=\"status != null\"> AND status = #{status} </if>",
            "</where>",
            "ORDER BY create_time DESC",
            "LIMIT #{limit} OFFSET #{offset}",
            "</script>"
    })
    List<Sample> list(@Param("sampleId") Long sampleId,
                      @Param("orderId") Long orderId,
                      @Param("sampleType") String sampleType,
                      @Param("status") Integer status,
                      @Param("limit") int limit,
                      @Param("offset") int offset);

    @Select({
            "<script>",
            "SELECT COUNT(1) FROM sample",
            "<where>",
            "  <if test=\"sampleId != null\"> AND sample_id = #{sampleId} </if>",
            "  <if test=\"orderId != null\"> AND order_id = #{orderId} </if>",
            "  <if test=\"sampleType != null and sampleType != ''\"> AND sample_type = #{sampleType} </if>",
            "  <if test=\"status != null\"> AND status = #{status} </if>",
            "</where>",
            "</script>"
    })
    long count(@Param("sampleId") Long sampleId,
               @Param("orderId") Long orderId,
               @Param("sampleType") String sampleType,
               @Param("status") Integer status);

    @Select("SELECT status AS status, COUNT(1) AS cnt FROM sample GROUP BY status")
    java.util.List<com.example.hospital.domain.dto.StatusCount> stats();
}